# -*- coding:utf-8 -*-
"""
作者：MySoul
日期：2023年10月15日
"""
import json
import os
import re
import traceback
from datetime import datetime

import requests
from socks import ProxyError

from service import LogRecoderService


def read_cookie_from_file(file_name):
    cookies = []
    try:
        for line in open(file_name, "r"):
            cookies.append(json.loads(line))
    except FileNotFoundError:
        return False, None
    except Exception as e:
        LogRecoderService.logger.error(f"cookie读取失败：{e}")
        return False, None
    return True, cookies


def save_cookie_to_file(file_name, cookies):
    try:
        with open(file_name, 'w') as file:
            for cookie in cookies:
                file.write(f"{json.dumps(cookie)}\n")
            LogRecoderService.logger.info(f"cookie写入成功：{file_name}")
    except Exception as e:
        LogRecoderService.logger.error(f"cookie写入失败！{file_name}：：：{e}")


def remove_cookie_from_file(file_name):
    try:
        os.remove(file_name)
        LogRecoderService.logger.info(f"cookie删除成功：{file_name}")
    except OSError as e:
        LogRecoderService.logger.error(f"cookie删除失败！{file_name}：：：{e}")


def write_error_file(cur_dir, tips):
    # 检测 cur_dir 目录是否存在，如果不存在则创建
    if not os.path.exists(cur_dir):
        os.makedirs(cur_dir)
    # 使用traceback进行打印调试错误并保存错误日志
    LogRecoderService.logger.debug("程序正在将错误写入文件……")
    with open(f'{cur_dir}error.txt', 'a') as f:
        f.write(f"{tips}\n")
        traceback.print_exc(file=f)  # 指定文件保存路径


def writeLatestTime(pathFile, latestTime):
    flag = os.path.exists(pathFile)
    if flag:
        with open(pathFile, "w") as f:
            f.write(latestTime)
            return "文件写入成功~"
    else:
        return "文件写入失败！"


# 提取字符串中的数字
def getNumberFromStr(str):
    pattern = re.compile("\d+")
    result = pattern.findall(str)
    return result


def getLatestTime(pathFile):
    flag = os.path.exists(pathFile)
    if flag:
        with open(pathFile, "r") as f:
            result = f.read()
    else:
        file_dir = pathFile.split("/")[:-1]
        flag = False
        if len(file_dir) > 0:
            file_dir = "/".join(file_dir)
        else:
            file_dir = pathFile.split("\\")[:-1]
            file_dir = "\\".join(file_dir)
        flag = os.path.exists(file_dir)
        if not flag:
            os.mkdir(file_dir)
        with open(pathFile, "w") as f:
            result = getNow('%Y-%m-%d %H:%M:%S')
            f.write(result)
    return result

    # 字符串日期比较大小


def timeCompare(latest_time, send_time):
    latest_time = latest_time.strip()
    send_time = send_time.strip()
    format_pattern = '%Y-%m-%d %H:%M:%S'
    # datetime.strptime() 以指定的格式进行输出
    result = datetime.strptime(latest_time, format_pattern) >= datetime.strptime(send_time, format_pattern)
    return result


def getUrlFromStr(str):
    pattern = re.compile(r"/jsxsd/ggly/ggly_show\?ggid=[A-Z0-9]+")
    result = pattern.search(str)
    return result.group(0)


def getNow(format):
    return datetime.now().strftime(format)


def removeAllFiles(path):
    try:
        for filename in os.listdir(path):
            file_path = os.path.join(path, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)
    except Exception as e:
        # 不处理此错误
        pass


def hasSupportedExtension(fileName):
    supported_extensions = [".ppt", ".pptx", ".rar", ".doc", ".docx", ".pdf", ".xls", ".xlsx", ".txt", ".jpg", ".jpeg",
                            ".png", ".7z"]
    for extension in supported_extensions:
        if fileName.lower().endswith(extension):
            return True
    return False


def getUrlFromStrTwo(str):
    pattern = r"'([^']*)'"
    match = re.search(pattern, str)
    if match:
        extracted_value = match.group(1)
    else:
        extracted_value = ""
        print("No match found.")
    return extracted_value


def getNetWorkStatus(url):
    try:
        resp = requests.get(url)
        status = str(resp.status_code)
        return status
    except ProxyError as e:
        return "403"
    except Exception as e:
        return "202112094263"


# 判断链接类型是否为MIME类型（在线预览类型）
def checkContentType(url):
    response = requests.head(url)  # 发送 HEAD 请求获取响应头信息
    content_type = response.headers.get('Content-Type')  # application/pdf
    # 预期的文件类型对应的 Content-Type
    expected_content_types = [
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/pdf',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/plain',
        'text/markdown'
    ]
    for expected_type in expected_content_types:
        if content_type is None:
            return False
        if content_type.startswith(expected_type):
            return True
    return False


def getSuffix(fileName):
    # 提取文件名中的后缀名
    suffix = fileName.split(".")[-1]
    return suffix


def getAllFiles(path):
    # 检测 path 目录是否存在，如果不存在则创建
    if not os.path.exists(path):
        os.makedirs(path, exist_ok=True)
    file_paths = []
    # 获取文件夹中的所有文件名
    file_list = os.listdir(path)
    # 过滤出文件
    for file_name in file_list:
        file_path = os.path.join(path, file_name)
        if os.path.isfile(file_path):
            file_paths.append(file_path)
    return file_paths


def getFileStatus(pathFile):
    flag = os.path.exists(pathFile)
    if flag:
        return True
    else:
        return False


def getFileContent(pathFile):
    with open(pathFile, "r") as f:
        result = f.read()
        return result


def removeFile(pathFile):
    flag = getFileStatus(pathFile)
    if flag:
        os.remove(pathFile)
        result = True
    else:
        result = False
    return result


if __name__ == '__main__':
    code = checkContentType(
        "https://jiaowu.scetc.edu.cn/ewebeditor/uploadfile/20230711085456633001.xls")
    print(code)
